import React, { useState, useEffect } from 'react';
import { CgEye } from 'react-icons/cg';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Alert, AlertDescription } from './ui/alert';
import { Progress } from './ui/progress';
import { getVsCodeApi } from '../lib/vscode-api';
import type { MiniProgramCI } from 'miniprogram-ci/dist/@types/types';

interface PreviewSectionProps {
  projectPath: string;
  privateKeyPath: string;
  appid: string;
  type: string;
  showToast: (title: string, description: string, type: 'success' | 'error' | 'info') => void;
  setLoading: (loading: boolean) => void;
}

const PreviewSection: React.FC<PreviewSectionProps> = ({
  projectPath,
  privateKeyPath,
  appid,
  type,
  showToast,
  setLoading,
}) => {
  const [version, setVersion] = useState<string>('');
  const [desc, setDesc] = useState<string>('');
  const [progress, setProgress] = useState<number>(0);
  const [progressStatus, setProgressStatus] = useState<MiniProgramCI.ITaskStatus | null>(null);
  const [isPreviewing, setIsPreviewing] = useState<boolean>(false);
  const [qrcode, setQrcode] = useState<string>('');

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      const message = event.data;
      
      switch (message.command) {
        case 'previewProgress':
          if (message.data) {
            const taskStatus = message.data as MiniProgramCI.ITaskStatus;
            setProgressStatus(taskStatus);
            // 根据状态估算进度百分比
            switch (taskStatus.status) {
              case 'doing':
                setProgress(50);
                break;
              case 'done':
                setProgress(100);
                break;
              case 'fail':
                setProgress(0);
                break;
              case 'warn':
                setProgress(75);
                break;
              case 'info':
                setProgress(25);
                break;
              default:
                setProgress(0);
            }
          }
          break;
          
        case 'previewResult':
          setLoading(false);
          setIsPreviewing(false);
          
          if (message.data.success) {
            setQrcode(message.data.result.qrcode || '');
            showToast('预览成功', '预览二维码已生成', 'success');
          } else {
            setQrcode('');
            showToast('预览失败', message.data.error || '生成预览二维码失败', 'error');
          }
          break;
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [showToast, setLoading]);

  const handlePreview = async () => {
    if (!projectPath || !privateKeyPath || !appid) {
      showToast('错误', '请确保已配置项目路径、私钥路径和 AppID', 'error');
      return;
    }

    setLoading(true);
    setIsPreviewing(true);
    setProgress(0);
    setQrcode('');
    
    // 发送预览请求到扩展
    getVsCodeApi().postMessage({
      command: 'preview',
      data: { projectPath, privateKeyPath, appid, type, version, desc }
    });
    
    showToast('预览已提交', '正在生成预览二维码...', 'info');
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <CgEye className="h-5 w-5" />
            预览小程序
          </CardTitle>
          <CardDescription>
            生成预览二维码，用于在真机上预览小程序效果
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="preview-version">版本号</Label>
              <Input
                id="preview-version"
                placeholder="例如：1.0.0"
                value={version}
                onChange={(e) => setVersion(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="preview-desc">版本描述</Label>
              <Input
                id="preview-desc"
                placeholder="版本更新描述"
                value={desc}
                onChange={(e) => setDesc(e.target.value)}
              />
            </div>
          </div>
          
          <Alert>
            <AlertDescription>
              确保项目已经构建完成，且包含了最新的代码变更。
            </AlertDescription>
          </Alert>

          {isPreviewing && (
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span>{progressStatus?.message || '生成预览中...'}</span>
                <span>{Math.round(progress)}%</span>
              </div>
              <Progress value={progress} className="w-full" />
              {progressStatus && (
                <div className="text-xs text-gray-500">
                  状态: {progressStatus.status} - {progressStatus.id}
                </div>
              )}
            </div>
          )}

          {qrcode && (
            <div className="space-y-2">
              <Label>预览二维码</Label>
              <div className="flex justify-center p-4 bg-gray-50 rounded-lg">
                <div className="max-w-[200px] max-h-[200px]">
                  <img
                    src={qrcode}
                    alt="小程序预览二维码"
                    className="w-full h-auto object-contain"
                  />
                </div>
              </div>
              <p className="text-sm text-gray-600 text-center">
                使用微信扫描二维码预览小程序
              </p>
            </div>
          )}

          <Button
            onClick={handlePreview}
            disabled={!projectPath || !privateKeyPath || !appid || isPreviewing}
            className="w-full"
          >
            {isPreviewing ? '生成中...' : '生成预览二维码'}
          </Button>
        </CardContent>
      </Card>
    </div>
  );
};

export default PreviewSection;